package com.ruoyi.tcp.entity;

import com.ruoyi.tcp.messager.CustomerProtocol;
import com.ruoyi.tcp.util.TcpAesUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Objects;

/**
 * @author 蒋翔 SY100242
 * @date 2024/8/7 14:25
 * @email SY100242@hnlens.com
 */
@Setter
@Getter
@ToString
public abstract class CustomerBaseEntity extends CustomerProtocol {

    private static final long serialVersionUID = 1L;

    //版本
    protected Integer version;
    //数据长度
//    protected Integer len;
    //数据序列号
    protected Long serializeNumber;
    //命令类型
    protected String typeStr;


    //获取渠道字节数组
    public byte[] getChannelNoBytes() {
        return TcpAesUtil.intToByteArray(getChannelNo().intValue());
    }

    //获取版本字节数组
    public byte[] getVersionBytes() {
        return TcpAesUtil.intToByteArray(getVersion().intValue());
    }

    //获取设备序列号字节数组
    public byte[] getSerialNumberBytes() {
        return TcpAesUtil.longToByteArray8(serializeNumber);
    }

    //获取命令行字节数组
    public byte[] getTypeBytes() {
        return TcpAesUtil.intToByteArray(Integer.parseInt(typeStr.substring(2)));
    }


    public abstract byte[] getOtherBytes();

    public byte[] createEncryptBytes(String key) {
        //明文
        String needEncryptStr = getNeedEncryptStr();
        byte[] encryptBytes = TcpAesUtil.encrypt(TcpAesUtil.alignByte(needEncryptStr), key);
        return encryptBytes;
    }

    //获取需要加密的数据
    private String getNeedEncryptStr() {
        byte[] serialNumberBytes = getSerialNumberBytes();
        byte[] typeBytes = getTypeBytes();
        byte[] otherBytes = getOtherBytes();

        StringBuilder sb = new StringBuilder();
        //版本
        sb.append(TcpAesUtil.byte2hex(getVersionBytes()));

        int size = serialNumberBytes.length + typeBytes.length;
        if (Objects.nonNull(otherBytes)) {
            size += otherBytes.length;
        }
        byte[] lenBytes = TcpAesUtil.intToByteArray(size);
        //数据长度
        sb.append(TcpAesUtil.byte2hex(lenBytes));
        //序列号

        sb.append(TcpAesUtil.byte2hex(serialNumberBytes));
        //命令类型
        sb.append(TcpAesUtil.byte2hex(typeBytes));

        if (Objects.nonNull(otherBytes)) {
            //其他
            sb.append(TcpAesUtil.byte2hex(otherBytes));
        }
        String crcStr = TcpAesUtil.createCrcStr(sb.toString());
        sb.append(crcStr);

        return sb.toString();
    }
}
